package com.tangoj.common.common;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tangoj.common.constant.CommonConstant;
import com.tangoj.common.exception.BusinessException;
import com.tangoj.common.exception.ThrowUtils;
import com.tangoj.common.utils.SqlUtil;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 分页请求
 */
@Data
public class PageRequest implements Serializable {

    /**
     * 当前页号
     */
    private Long current;

    /**
     * 页面大小
     */
    private Long pageSize;

    /**
     * 排序字段
     */
    private String orderByColumn;

    /**
     * 排序顺序（默认升序）
     */
    private String isAsc = CommonConstant.SORT_ORDER_ASC;

    public <T> Page<T> build() {

        // 限制爬虫
        ThrowUtils.throwIf(getPageSize() > 100, ErrorCode.PARAMS_ERROR);

        Long current = (Long) ObjectUtil.defaultIfNull(getCurrent(), 1);
        Long pageSize = (Long) ObjectUtil.defaultIfNull(getPageSize(), 10);

        Page<T> page = new Page<>(current, pageSize);
        List<OrderItem> orderItems = buildOrderItem();
        if (orderItems == null || orderItems.size() <= 0) {
            return page;
        }
        page.addOrder(orderItems);

        return page;
    }

    /**
     * 构建排序
     * 支持的用法如下:
     * {isAsc:"asc",orderByColumn:"id"} order by id asc
     * {isAsc:"asc",orderByColumn:"id,createTime"} order by id asc,create_time asc
     * {isAsc:"desc",orderByColumn:"id,createTime"} order by id desc,create_time desc
     * {isAsc:"asc,desc",orderByColumn:"id,createTime"} order by id asc,create_time desc
     */
    private List<OrderItem> buildOrderItem() {
        if (StringUtils.isBlank(orderByColumn) || StringUtils.isBlank(isAsc)) {
            return null;
        }
        String orderBy = SqlUtil.escapeOrderBySql(orderByColumn);
        orderBy = StrUtil.toUnderlineCase(orderBy);

        // 兼容前端排序类型
        isAsc = StringUtils.replaceEach(isAsc, new String[]{"ascending", "descending"}, new String[]{"asc", "desc"});

        String[] orderByArr = orderBy.split(",");
        String[] isAscArr = isAsc.split(",");
        if (isAscArr.length != 1 && isAscArr.length != orderByArr.length) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        List<OrderItem> list = new ArrayList<>();
        // 每个字段各自排序
        for (int i = 0; i < orderByArr.length; i++) {
            String orderByStr = orderByArr[i];
            String isAscStr = isAscArr.length == 1 ? isAscArr[0] : isAscArr[i];
            if ("asc".equals(isAscStr)) {
                list.add(OrderItem.asc(orderByStr));
            } else if ("desc".equals(isAscStr)) {
                list.add(OrderItem.desc(orderByStr));
            } else {
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
        }
        return list;
    }
}
